package com.dqv5.shorturl.service;

import com.dqv5.shorturl.config.Constants;
import com.dqv5.shorturl.entity.URLRecord;
import com.dqv5.shorturl.exception.CommonShortException;
import com.dqv5.shorturl.repository.URLRecordRepository;
import com.dqv5.shorturl.service.MainService;
import com.dqv5.shorturl.util.RadixUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Clock;
import java.util.*;

/**
 * @author duqian
 * @date 2020/6/5
 */
@Service
@Slf4j
public class MainService {
    @Value("${shorturl.max-code-length:3}")
    private Integer maxCodeLength;
    @Autowired
    private URLRecordRepository urlRecordRepository;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String shortUrl(String originUrl) {
        String nextCode = getNextCode();
        URLRecord record = new URLRecord();
        record.setShortCode(nextCode);
        record.setOriginUrl(originUrl);
        urlRecordRepository.save(record);
        return nextCode;
    }

    public String getNextCode() {
        Long size = redisTemplate.opsForList().size(Constants.SHORTURL_CODE_LIST_KEY);
        if (size == 0) {
            throw new CommonShortException("无可用的短连接");
        }
        String nextCode = redisTemplate.opsForList().leftPop(Constants.SHORTURL_CODE_LIST_KEY);
        return nextCode;
    }
}
